package com.tgu.home_action.controller;

import com.tgu.home_action.pojo.Admin;
import com.tgu.home_action.pojo.ResponseData;
import com.tgu.home_action.pojo.Volunteer;
import com.tgu.home_action.pojo.VolunteerInformation;
import com.tgu.home_action.pojo.annotation.ApiJsonObject;
import com.tgu.home_action.pojo.annotation.ApiJsonProperty;
import com.tgu.home_action.pojo.annotation.MyLog;
import com.tgu.home_action.pojo.exception.IMException;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.VolunteerService;
import io.jsonwebtoken.ExpiredJwtException;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.Pattern;


import java.io.IOException;
import java.util.Map;

@Api(tags = "志愿者端的用户管理")
@Validated
@RestController
@RequestMapping("/volunteer")
public class VolunteerController {
    @Autowired
    private Logger logger;
    @Autowired
    private VolunteerService volunteerService;

    @MyLog(actionId = 1, role = "volunteer", type = 2)
    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseData<Volunteer> login(@ApiJsonObject(name = "VolunteerLoginCode", value = {
            @ApiJsonProperty(key = "code", description = "从微信获取的code")
    }) @RequestBody Map<String, Object> param) {
        return volunteerService.login((String) param.get("code"));
    }

    /**
     * 更新微信获取的信息
     *
     * @param param：信息
     * @param volunteerUser：当前登录的用户
     * @return responseData
     */
    @MyLog(actionId = 3, role = "volunteer", type = 3)
    @ApiOperation("更新微信获取的信息")
    @PreAuthorize("hasRole('volunteer')")
    @PostMapping("/userinfo")
    public ResponseData<Object> updateInfo(@ApiJsonObject(name = "volunteerUserInfo", value = {
            @ApiJsonProperty(key = "encryptedData", description = "加密字符串"),
            @ApiJsonProperty(key = "iv", description = "从微信获取的iv")
    }) @RequestBody Map<String, Object> param, @ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteerUser) {
        String encryptedData = (String) param.get("encryptedData");
        String iv = (String) param.get("iv");
        return volunteerService.updateUserinfo(encryptedData, iv, volunteerUser);
    }

    @ApiOperation("更新Token")
    @PostMapping("/refresh")
    public ResponseData<Object> refreshToken(@ApiJsonObject(name = "VolunteerRefreshToken",
            value = @ApiJsonProperty(key = "refreshToken", description = "refreshToken")) @RequestBody Map<String, Object> param) {
        try {
            return volunteerService.refreshToken((String) param.get("refreshToken"));
        } catch (ExpiredJwtException e) {
            logger.warn("token已过期");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.REFRESH_TOKEN_IS_EXPIRED.getMessage(), ResponseState.REFRESH_TOKEN_IS_EXPIRED.getValue());
        } catch (Exception e) {
            System.out.println(e);
            logger.error("发生错误");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.REFRESH_TOKEN_IS_ERROR.getMessage(), ResponseState.REFRESH_TOKEN_IS_ERROR.getValue());
        }
    }

    @ApiOperation("绑定志愿者手机号时获取验证码")
    @PreAuthorize("hasRole('volunteer')")
    @GetMapping("/getBindCode")
    public ResponseData<Object> getCode(@ApiParam(name = "phone", value = "手机号", required = true)
                                        @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式错误") @RequestParam String phone, @ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteerUser) {
        return volunteerService.getBindCode(phone, volunteerUser);
    }

    @ApiOperation("修改志愿者手机号时获取验证码")
    @PreAuthorize("hasRole('volunteer')")
    @GetMapping("/getUpdateCode")
    public ResponseData<Object> getUpdateCode(@ApiParam(name = "phone", value = "手机号", required = true)
                                              @Pattern(regexp = "^[1]([3-9])[0-9]{9}$", message = "手机号格式错误") @RequestParam String phone, @ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteerUser) {
        return volunteerService.getUpdateCode(phone, volunteerUser);
    }

    @MyLog(actionId = 5, role = "volunteer", type = 3)
    @ApiOperation("绑定/修改手机号")
    @PreAuthorize("hasRole('volunteer')")
    @ApiResponses({
            @ApiResponse(message = "该手机号已经被绑定", code = 108),
            @ApiResponse(message = "验证码未获取或已过期", code = 109),
            @ApiResponse(message = "验证码错误", code = 110)
    })
    @PostMapping("/bindPhone")
    public ResponseData<Object> bindPhone(@ApiJsonObject(name = "VolunteerBindPhone",
            value = {@ApiJsonProperty(key = "phone", description = "手机号"),
                    @ApiJsonProperty(key = "code", description = "验证码")
            }) @RequestBody Map<String, Object> param, @ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteerUser) {
        try {
            String phone = (String) param.get("phone");
            String code = (String) param.get("code");
            return volunteerService.bindPhone(phone, code, volunteerUser);
        } catch (DuplicateKeyException e) {
            logger.error("该手机号已被绑定");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.PHONE_IS_EXIST.getMessage(), ResponseState.PHONE_IS_EXIST.getValue());
        }
    }

    @ApiOperation("志愿者上传图片")
    @PreAuthorize("hasRole('volunteer')")
    @PostMapping("/photo")
    public ResponseData<String> uploadPhoto(@RequestParam(required = true, name = "photo") MultipartFile photo, @ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteerUser) {
        try {
            return volunteerService.uploadPhoto(photo, volunteerUser);
        } catch (IOException e) {
            logger.error("志愿者上传图片时获得文件流失败");
            logger.error(e.getMessage());
            return new ResponseData<>(ResponseState.NOT_CAN_GET_FILE_STREAM.getMessage(), ResponseState.NOT_CAN_GET_FILE_STREAM.getValue());
        }
    }

    @MyLog(actionId = 7, type = 3, role = "volunteer")
    @ApiOperation("更换头像")
    @PreAuthorize("hasRole('volunteer')")
    @PutMapping("/avatar")
    public ResponseData<String> updateAvatar(@ApiJsonObject(name = "VolunteerAvatarUrl", value = @ApiJsonProperty(key = "avatarUrl", description = "头像链接"))
                                             @RequestBody Map<String, Object> param, @ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteerUser) {
        return volunteerService.updateAvatar((String) param.get("avatarUrl"), volunteerUser);
    }

    @ApiOperation("查询志愿者数量")
    @GetMapping("/number")
    public ResponseData<Integer> getVolunteerNumber(@RequestBody VolunteerInformation volunteerInformation) {
        return volunteerService.getVolunteerNumber(volunteerInformation);
    }

    @ApiOperation("查询注册志愿者数量")
    @GetMapping("/registerNumber")
    public ResponseData<Integer> getRegisterVolunteerNumber(Admin admin) {
        return volunteerService.getRegisterVolunteerNumber(admin);
    }

    @ApiOperation("查询在线的志愿者数量")
    @GetMapping("/onlineNumber")
    public ResponseData<Integer> getOnlineVolunteerNumber(VolunteerInformation volunteerInformation) {
        return volunteerService.getOnlineVolunteerNumber(volunteerInformation);
    }


    @ApiOperation("IM获取UserSig")
    @PreAuthorize("hasRole('volunteer')")
    @GetMapping("/im/userSig")
    public ResponseData<String> getUserSig(@ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteer) {
        try {
            return volunteerService.getUserSig(volunteer);
        } catch (IMException e) {
            return new ResponseData<>(e.getMessage(), ResponseState.IM_ERROR.getValue());
        }
    }

    @ApiOperation("加入群组")
    @PreAuthorize("hasRole('volunteer')")
    @PostMapping("joinGroup")
    public ResponseData<Object> joinGroup(@ApiJsonObject(name = "VolunteerJoinGroup",value = {
            @ApiJsonProperty(key = "caseId",description = "案件ID")
    })@RequestBody Map<String,Object> param,@ApiIgnore @ModelAttribute("volunteerUser") Volunteer volunteer){
        Integer caseId= (Integer) param.get("caseId");
        return volunteerService.joinGroup(caseId,volunteer);
    }

    @ApiOperation("swagger测试接口")
    @PostMapping("/zzzzzzzzzzzzzzzzzz")
    public void zzzzzzzzzzzzzzzzzzzzzzz(@ApiJsonObject(name = "zzzzzzzzzzzzzzz", value = {
            @ApiJsonProperty(key = "encryptedData", description = "加密字符串"),
            @ApiJsonProperty(key = "iv", description = "从微信获取的iv")
    }) @RequestBody Map<String, Object> param) {

    }
}
